﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.MenuCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Impl;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.MenuHandler
{
    public class MenuUpdateCommandHandlers : IRequestHandler<MenuUpdateCommand, ApiResult<int>>
    {
        private readonly IMenuRepository _menuRepository;
        private readonly IFunctionRepository _functionRepository;
        private readonly ILogger<MenuUpdateCommandHandlers> _logger;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;
        private readonly RedisConnectionService _redisConnectionService;
        private readonly IUserInfoRepository _userInfoRepository;


        public MenuUpdateCommandHandlers(IMenuRepository menuRepository, IFunctionRepository functionRepository, ILogger<MenuUpdateCommandHandlers> logger, IMapper mapper, IConfiguration configuration, RedisConnectionService redisConnectionService, IUserInfoRepository userInfoRepository)
        {
            _menuRepository = menuRepository;
            _functionRepository = functionRepository;
            _logger = logger;
            _mapper = mapper;
            _configuration = configuration;
            _redisConnectionService = redisConnectionService;
            _userInfoRepository = userInfoRepository;
        }

        public async Task<ApiResult<int>> Handle(MenuUpdateCommand request, CancellationToken cancellationToken)
        {
            //修改菜单和修改菜单下的按钮不使用mapper
            await _functionRepository.BeginTransactionAsync();
            try
            {



                var menulist = await _menuRepository.GetAllAsunc(m => m.menu_name == request.UpdateName && m.sys_id == request.sys_id && m.del_flag == 0);
                var menu = menulist.FirstOrDefault();
                if (_configuration["Redis:Redisif"] == "1")
                {
                    await _redisConnectionService.DeleteAsync($"MenuTree_{request.sys_id}");
                    await _redisConnectionService.DeleteAsync($"Menu_{request.sys_id}");
                    var userid = await _userInfoRepository.GetAllAsunc(u => u.sys_id == request.sys_id && u.del_flag == 0);
                    await _redisConnectionService.DeleteAsync($"user:{userid}:{request.sys_id}:menuIds");
                }

                if (menu == null)
                {
                    return new ApiResult<int>(ResultCode.Error, "菜单不存在");
                }
                menu.menu_name = request.UpdateName;
                menu.create_date = DateTime.UtcNow;
                menu.menu_url = request.dto.menu_url;
                menu.perms = request.dto.perms;
                menu.type = request.dto.type;
                menu.menu_icon = request.dto.menu_icon;
                menu.order_num = request.dto.order_num;
                menu.parent_id = request.dto.parent_id;
                menu.update_by = request.UpdateName;
                var result = await _menuRepository.UpdateAsync(menu);
                if (request.dto.Button.Count > 0)
                {
                    //删除菜单下的按钮
                    var funlist = await _functionRepository.GetAllAsunc(m => m.menu_id == menu.id);
                    foreach (var item in funlist)
                    {
                        await _functionRepository.DeleteAsync(item.id);
                    }
                    //修改菜单下的按钮
                    foreach (var item in request.dto.Button)
                    {
                        var fun = _mapper.Map<sys_function>(item);
                        fun.id = 0;
                        fun.create_by = request.UpdateName;
                        await _functionRepository.AddAsync(fun);
                    }
                }
                _logger.LogInformation($"修改菜单{request.UpdateName}成功，系统：{request.sys_id},添加参数{request.dto} ");
                await _functionRepository.CommitTransactionAsync();
                return new ApiResult<int>() { Data = result };
            }
            catch (Exception ex)
            {
                await _functionRepository.RollbackTransactionAsync();
                _logger.LogError($"修改菜单{request.UpdateName}失败，系统：{request.sys_id}，错误信息：{ex.Message}");
                return new ApiResult<int>(ResultCode.Error, "修改菜单失败");
            }
        }
    }
}
